const gulp = require('gulp');
const del = require('del');
// 获取 uglify 模块（用于压缩 JS）
const uglify = require('gulp-uglify');
// 压缩css
const minify = require('gulp-minify-css');
// 压缩html
const htmlmin = require('gulp-htmlmin');

// 输出目录
var distDir = './dist/';
//获取参数
var argv = require('minimist')(process.argv.slice(2));

var task = {
  minjs: function(){
    /*
    * 必须：使用 --source=xxx 指定要扫描的目录
    * 可选：使用 --mod=xxx|xxx  指定要压缩的js
    * */
    var mod = argv.mod ? function(){
      return '(' + argv.mod.replace(/,/g, '|') + ')';
    }() : ''
      , src = [
      './src/js/**/*' + mod + '.js'
    ];
    return gulp.src(src)
      .pipe(uglify())//压缩js
      .pipe(gulp.dest(distDir + '/js'));
  },
  mv: function(src, dist){
    return gulp.src(src)
      .pipe(gulp.dest(distDir + dist));
  },
  mincss: function(){
    var src = [
      './src/css/**/*.css'
    ]
    return gulp.src(src)
      .pipe(minify({
        compatibility: 'ie7'
      }))
      .pipe(gulp.dest(distDir + '/css'));
  },
  minhtml: function(){
    var src = './src/view/**/*.html'
      , options = {
      collapseWhitespace: true,
      collapseBooleanAttributes: true,
      removeComments: true,
      removeEmptyAttributes: true,
      removeScriptTypeAttributes: true,
      removeStyleLinkTypeAttributes: true,
      minifyJS: true,
      minifyCSS: true,
    };

    return gulp.src(src)
      .pipe(htmlmin(options))
      .pipe(gulp.dest(distDir + '/views'))
  }
}

gulp.task('js', task.minjs);
gulp.task('mv', function(cb){
  task.mv('./src/plugin/**/*', '/plugin');
  task.mv('./src/fonts/**/*', '/fonts');
  task.mv('./src/images/**/*', '/images');
  cb()
});
gulp.task('css', task.mincss);
gulp.task('html', task.minhtml);
//清理
gulp.task('clear', function(cb){
  return del([distDir + '*'], cb);
});

gulp.task('all', gulp.series('clear', 'js', 'css', 'html', 'mv'))
